import React, { useState } from 'react'
import {
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Typography,
  Space,
  Switch,
  message,
  Button,
  Menu,
  Dropdown,
} from 'antd'

import { inject, observer } from 'mobx-react'

import {
  QuestionCircleOutlined,
  PlusSquareOutlined,
  CaretDownOutlined,
} from '@ant-design/icons'
import HomeStore from '../../stores/HomeStory'
import { ExpandableConfig } from 'rc-table/lib/interface'

export interface User {
  key: string
  name: string
  age: number
  address: string
  status: boolean
}

interface SelectTableProps {
  HomeStore?: HomeStore
  setUncheck?: Function
  setSelectColumnKeys?: Function
  setSelectColumns?: Function
  expandable?: ExpandableConfig<any> | undefined
  dataSource?: any[]
  columns?: any[]
}

let dataSource: User[] = []
let tempStatus = false
for (let i = 0; i < 100; i++) {
  tempStatus = !tempStatus
  dataSource.push({
    key: i + '',
    name: `Edward King ${i}`,
    age: i,
    address: `London, Park Lane no. ${i}`,
    status: tempStatus,
  })
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean
  dataIndex: string
  title: any
  inputType: 'number' | 'text'
  record: User
  index: number
  children: React.ReactNode
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  )
}

const SelectTable: React.FC<SelectTableProps> = (props: SelectTableProps) => {
  const {
    setUncheck,
    setSelectColumnKeys,
    setSelectColumns,
    HomeStore,
    expandable,
  } = props

  const [form] = Form.useForm()
  const [editingKey, setEditingKey] = useState('')
  const [data, setData] = useState(dataSource)
  const [performBatch, setPerformBatch] = useState(false)

  const isEditing = (record: User) => record.key === editingKey

  // 进入编辑
  const edit = (record: Partial<User> & { key: React.Key }) => {
    form.setFieldsValue({ ...record })
    setEditingKey(record.key)
  }

  // 退出编辑
  const cancelEdit = () => {
    setEditingKey('')
  }

  // 保存编辑内容
  const save = async (key: React.Key) => {
    console.log(key)

    try {
      const row = (await form.validateFields()) as User

      const newData = [...dataSource]
      const index = newData.findIndex((item) => key === item.key)
      if (index > -1) {
        const item = newData[index]
        newData.splice(index, 1, {
          ...item,
          ...row,
        })
        setData(newData)
        setEditingKey('')
      } else {
        newData.push(row)
        setData(newData)
        setEditingKey('')
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo)
    }
  }

  // 取消删除
  const cancel = () => {
    message.error('Click on No')
  }

  // 删除某行
  const handleDelete = (user: User) => {
    console.log('delete row key:', user.key)
    setData([...data.filter((item) => item.key !== user.key)])
  }

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: 'Age',
      dataIndex: 'age',
      editable: true,
    },
    {
      title: 'Address',
      dataIndex: 'address',
      editable: true,
    },
    {
      title: 'Action',
      key: 'action',
      render: (text: any, record: User) => {
        const editable = isEditing(record)
        return (
          <Space size='middle'>
            {!editable ? (
              <>
                <Typography.Link onClick={() => edit(record)}>
                  编辑
                </Typography.Link>
                <Popconfirm
                  title={`确定删除【${text.name}】吗？`}
                  onConfirm={() => handleDelete(record)}
                  onCancel={cancel}
                  okText='确认'
                  cancelText='取消'
                  icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                >
                  <Typography.Link>删除</Typography.Link>
                </Popconfirm>
                <Switch
                  checkedChildren='开启'
                  unCheckedChildren='关闭'
                  defaultChecked={text.status}
                />
              </>
            ) : (
              <>
                <Typography.Link onClick={() => save(record.key)}>
                  保存
                </Typography.Link>
                <Typography.Link onClick={() => cancelEdit()}>
                  取消
                </Typography.Link>
              </>
            )}
          </Space>
        )
      },
    },
  ]

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col
    }
    return {
      ...col,
      onCell: (record: User) => ({
        record,
        inputType: col.dataIndex === 'age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    }
  })

  const onChange = (selectedRowKeys: any, selectedRows: any) => {
    console.log(selectedRowKeys, selectedRows)
    if (selectedRowKeys.length > 0) {
      setPerformBatch(true)
    } else {
      setPerformBatch(false)
    }
    if (setSelectColumnKeys) {
      setSelectColumnKeys(selectedRowKeys)
    }
    if (setSelectColumns) {
      setSelectColumns(selectedRows)
    }

    if (selectedRowKeys.length > 0) {
      if (setUncheck) {
        setUncheck(false)
      }
    } else {
      if (setUncheck) {
        setUncheck(true)
      }
    }
  }

  const rowSelection = {
    columnWidth: 100,
    onChange: onChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
    ],
  }

  const scroll = {
    scrollToFirstRowOnChange: false,
    x: '100%',
    y: 'calc(100vh - 194px - 180px)',
  }

  const handleMenuClick = (e: any) => {
    message.info('Click on menu item.')
    console.log('click', e)
  }

  const menu = (
    <Menu onClick={handleMenuClick} theme='dark'>
      <Menu.Item key='1' icon={<PlusSquareOutlined />}>
        批量删除
      </Menu.Item>
      <Menu.Item key='2' icon={<PlusSquareOutlined />}>
        批量开启
      </Menu.Item>
      <Menu.Item key='3' icon={<PlusSquareOutlined />}>
        批量关闭
      </Menu.Item>
    </Menu>
  )

  return (
    <Form form={form} component={false}>
      <Space size={4}>
        <Button type='primary' onClick={HomeStore?.changeAddUserDrawerVisible}>
          <PlusSquareOutlined />
          {HomeStore?.language === 'en_US' ? 'Add user' : '添加用户'}
        </Button>
        <Dropdown.Button
          onClick={HomeStore?.changeSelectTableVisible}
          overlay={HomeStore?.selectTableVisible ? menu : <div />}
          icon={
            HomeStore?.selectTableVisible && performBatch ? (
              <CaretDownOutlined />
            ) : null
          }
          type='primary'
        >
          {HomeStore?.language === 'en_US' ? 'Batch operate' : '批量操作'}
        </Dropdown.Button>
      </Space>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        pagination={{ responsive: true, onChange: cancelEdit }}
        rowSelection={HomeStore?.selectTableVisible ? rowSelection : undefined}
        scroll={scroll}
        columns={
          props.columns !== undefined && props.columns?.length > 0
            ? props.columns
            : mergedColumns
        }
        dataSource={props.dataSource !== undefined ? props.dataSource : data}
        expandable={expandable}
      />
    </Form>
  )
}

export default inject('HomeStore')(observer(SelectTable))
